package com.major.dawn.forkJoin;

import java.util.concurrent.*;

public class CountTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 2;

    private int start;

    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {

        int sum = 0;

        boolean canCompute = end - start <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum = sum + start;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask left = new CountTask(start, middle);
            CountTask right = new CountTask(middle + 1, end);
            left.fork();
            right.fork();
            Integer leftJoin = left.join();
            Integer rightJoin = right.join();
            sum = leftJoin + rightJoin;

        }
        return sum;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask countTask = new CountTask(1, 4);
        Future<Integer> submit = forkJoinPool.submit(countTask);
        Integer integer = submit.get();
        System.out.println(integer);

    }

}
